package com.ld.security.common.elastic.util;

import com.ld.security.common.core.util.ReflectionUtil;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.springframework.data.domain.Pageable;
import org.springframework.data.elasticsearch.core.SearchResultMapper;
import org.springframework.data.elasticsearch.core.aggregation.AggregatedPage;
import org.springframework.data.elasticsearch.core.aggregation.impl.AggregatedPageImpl;

import java.util.LinkedList;
import java.util.Map;

public class SimpSearchResultMapper implements SearchResultMapper {

    @Override
    public <T> AggregatedPage<T> mapResults(SearchResponse searchResponse, Class<T> aClass, Pageable pageable) {
        SearchHits hits = searchResponse.getHits();
        LinkedList<T> list =  new LinkedList<>();

        for (SearchHit hit : hits) {
            Map map =  hit.getSourceAsMap();
            if(hit.getHighlightFields() != null){
                hit.getHighlightFields().forEach((x,y) -> {
                    String text = y.getFragments()[0].toString();
                    map.put(x,text);
                });
                T seaContent1 =  ReflectionUtil.clone(map,aClass);
                list.add(seaContent1);
            }

        }

        AggregatedPageImpl<T> articleInfos =  new AggregatedPageImpl<>(list,pageable,hits.getTotalHits());

        return articleInfos;
    }
}
